/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package eulerframework;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Thor
 */
public class WebsiteParser {

    private static final String PROJECT_EULER_URL = "http://projecteuler.net/";
    private Random random;
    private String content;

    public WebsiteParser(int problemNumber){
        content = WebsiteReader.read(PROJECT_EULER_URL+"problem="+problemNumber);
        random = new Random();
    }

    public String getURL(){
        return PROJECT_EULER_URL;
    }

    public String getProblemDescription(){
        String problemDescription = "ERROR!";
        Pattern problemContentPattern = Pattern.compile("<div class=\"problem_content\" role=\"problem\">(.*?)</div>", Pattern.DOTALL);
        Matcher problemMatcher = problemContentPattern.matcher(content);
        if(problemMatcher.find()){
            problemDescription = problemMatcher.group(1);
        }
        problemDescription = fixRelativeURLs(problemDescription);
        return problemDescription;
    }

    private String fixRelativeURLs(String source){
        String result = source;
        Pattern sourceImagePattern = Pattern.compile("<img src='(.*?)'");
        Matcher sourceMatcher = sourceImagePattern.matcher(source);
        if(sourceMatcher.find()){
            for(int i = 0; i < sourceMatcher.groupCount(); i++){
                result = result.replace(sourceMatcher.group(i+1), PROJECT_EULER_URL+sourceMatcher.group(i+1));
            }
        }
        return result;
    }

    public String getCaptionURL(){
        return "http://projecteuler.net/captcha/image_show.php?ekey="+random.nextInt();
    }

}
